package cn.com.connected.common.aop;

import cn.com.connected.base.cache.CacheService;
import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.base.utils.StringTools;
import cn.com.connected.common.emnus.HttpParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static cn.com.connected.common.emnus.HttpParams.*;

/**
 * Created by shaomingsheng on 2021/07/03
 */
@Aspect
@Component
@Slf4j
@Order(10)
public class CaptchaAOP {

  @Resource
  private CacheService cacheService;

  @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public void pointcut1(){}

  @Pointcut("@annotation(cn.com.connected.base.annotations.Captcha)")
  public void Captcha() {}

  @Order(10)
  @Around("pointcut1() && Captcha()")
  public Object handlerLogin(ProceedingJoinPoint pjp)  throws Throwable{
    this.checkCaptcha();
    Object result =  pjp.proceed();
    return result;
  }


  private void checkCaptcha(){
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String icId = request.getHeader(HttpParams.UU1);
    String icValue = request.getHeader(IMAGE_CODE);

    if(StringUtils.isEmpty(icValue)){
      throw new BusinessException(ErrorCode.IMAGE_CODE_EMPTY);
    }
    String icCode = cacheService.getObject(StringTools.format(HttpParams.UU1,icId));
    if (StringUtils.isEmpty(icCode) || !icCode.equals(icValue)){
      throw new BusinessException(ErrorCode.IMAGE_CODE_ERROR);
    }

  }
}